<template>
	<div>
		<u-popup :show="login.show" @close="login.show = false" round="30rpx">
			<div class="login">
				<div class="tit">请先登录</div>
				<div class="buts">
					<!-- #ifndef H5 -->
					<div class="but"><u-button type="primary" shape="circle" open-type="getPhoneNumber"
							@getphonenumber="onGetPhoneNumber">授权手机号登录</u-button></div>
						<!-- #endif -->
					<!-- #ifdef H5 -->
					<div class="but"><u-button type="primary" shape="circle" open-type="getPhoneNumber"
							@click="tologin">授权手机号登录</u-button></div>
						<!-- #endif -->
				</div>
			</div>
		</u-popup>
	</div>
</template>

<script setup>
	let login = Vue.reactive({
		show: false,
	})

	let event

	async function tologin() {
		uni.showLoading({
			title: '加载中',
			mask: true,
		})
		var res = await $post('account/phone_login', {}, d => {
			uni.hideLoading()
			return d;
		})

		xaoi.store('user', res)

		login.show = false

		event(res)
	}

	async function onGetPhoneNumber(e) {
		if (e.detail.errMsg == "getPhoneNumber:ok") {

			let invite_id = xaoi.store('invite_id')

			let code = await new Promise(ok => uni.login({
				provider: 'weixin',
				success(res) {
					ok(res.code);
				}
			}))

			uni.showLoading({
				title: '加载中',
				mask: true,
			})
			var res = await $post('account/phone_login', {
				phone_code: e.detail.code,
				code: code,
				invite_id,
			}, d => {
				uni.hideLoading()
				return d;
			})

			xaoi.store('user', res)

			login.show = false

			event(res)
		}
	}

	defineExpose({
		user() {
			let user = xaoi.store('user')

			if (user) {
				return user
			}

			return new Promise(ok => {
				event = ok
				login.show = true
			})
		},
	})
</script>

<style lang="scss" scoped>
	.login {
		.tit {
			padding: 20rpx 0;
			text-align: center;
			font-size: 40rpx;
			font-weight: bold;
		}

		.buts {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 140rpx 0;

			.but {
				width: 80%;
				height: 80%;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>